package com.example.myanimator.scroll;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import java.util.List;

/**
 * @author tgw
 * @date 2021/11/22
 * @describe
 */


class ViewPagerImageAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener {



    private List<ImageView> imageViewList;
    private ViewPager mViewPager;
    private Context mContext;
    private int currentPosition2 = 1 ;

    public ViewPagerImageAdapter(List<ImageView> imageViewList, ViewPager mViewPager, Context mContext) {
        this.imageViewList = imageViewList;
        this.mViewPager = mViewPager;
        this.mContext = mContext;
        this.mViewPager.addOnPageChangeListener(this);
    }

    @Override
    public int getCount() {
        return imageViewList.size();
    }

    /**
     * 判断出去的view是否等于进来的view 如果为true直接复用
     */
    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    /**
     * 销毁预加载以外的view对象, 会把需要销毁的对象的索引位置传进来就是position
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(imageViewList.get(position));
    }

    /**
     * 创建一个view
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(imageViewList.get(position));
        return imageViewList.get(position);
    }



    @Override
    public void onPageScrollStateChanged(int state) {


    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageSelected(int position) {
        Log.d("tgw1", "onPageSelected: $position:"+position);
        currentPosition2 = position;

        if (currentPosition2 == 0) {
            mViewPager.setCurrentItem(imageViewList.size() - 2, false);//切换，不要动画效果
        } else if (currentPosition2 == imageViewList.size() - 1) {
            mViewPager.setCurrentItem(1, false);//切换，不要动画效果
        }
    }

}

